#include<vector>
#include<unordered_map>
#include<algorithm>
using namespace std;

class Solution {
public:
    int findMaxLength(vector<int>& nums) {
        unordered_map<int, int>map;
        int res = 0, count = 0;
        for (int i = 0; i < nums.size(); ++i) {
            count += nums[i] == 0 ? -1 : 1;
            if (count == 0)
                res = i + 1;
            else if (map.find(count) != map.end())
                res = max(res, i - map[count]);
            else
                map[count] = i;
        }
        return res;
    }
};